namespace Mytodotodaylist.Core.Schedule
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Timers;

    public class Scheduler
    {
        public delegate void TickHandler();
        public event TickHandler Tick;

        private Timer TheTimer;

        public bool IsRunning = false;

        public Scheduler():this(1000)
        {
        }

        public Scheduler(int periodInMiliseconds)
        {
            Tasks = new List<ITask>();

            TheTimer = new Timer(periodInMiliseconds);
            TheTimer.Elapsed += TheTimerElapsed;
        }

        private void TheTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (!IsRunning) return;

            if (Tick != null)
                Tick();

            RunAllTasks();
        }

        public List<ITask> Tasks { get; set;}

        public void Start()
        {
            IsRunning = true;
            TheTimer.Start();
        }

        public void Stop()
        {
            IsRunning = false;
            TheTimer.Stop();
        }

        public void RegisterTask(ITask task)
        {
            Tasks.Add(task);
        }

        public void RunAllTasks()
        {
            Tasks
                .ForEach(x=>x.Execute());

            Debug.WriteLine("Tick");
        }
    }
}